package cn.action.product;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.action.BaseAction;
import cn.beans.ProductCategory;
import cn.busiBean.ProductCategoryBean;

import com.opensymphony.xwork2.ActionContext;

@SuppressWarnings("unchecked")
public class ProductCategoryAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private ProductCategory pc;
	private List listPc;
	private Map pcMap = new HashMap<String, String>();
	private String pcId;
	private String parentPcId;
	private String errorinfo;
	private String islast;
	private List<ProductCategory>  listParent=new ArrayList<ProductCategory>();
	private Map<String, List<ProductCategory>> subMap=new HashMap<String, List<ProductCategory>>();
	
	
	/**
	 * 查找第一级的目录
	 * @throws Exception
	 */
	public String findProductParen() throws Exception{
		
		try{
			String hql = "FROM ProductCategory AS pc WHERE pc.parentId = ? ORDER BY pc.turnnumber";
			Object[] param = { "root" };
			listPc = findSomeByHQL.findDataByHql(hql, param);
			for (int i = 0; i <listPc.size(); i++) {
				ProductCategory pc = (ProductCategory)listPc.get(i);
				pcMap.put(pc.getId(), pc.getNameCn());
			}
			return SUCCESS;
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
			return null;
		}
	}
	/**
	 * 添加产品类目
	 * @throws Exception
	 */
	public void addProductCategory() throws Exception{
		try{
			String adminId = (String)ActionContext.getContext().getSession().get("adminId");
			if(null == adminId){
				this.sendMsgAjax("login", null);
			}else{
				if(null != pc.getId() && !"".equals(pc.getId().trim())){
					Object[] levelAndTurnnum = this.getLevelAndTurnnum(pc.getId());
					if(0 == (Integer)levelAndTurnnum[0] && 0 == (Integer)levelAndTurnnum[1]){
						this.sendMsgAjax("parentPc", null);
					}else{
						ProductCategory newPc = new ProductCategory();
						newPc.setNameCn(pc.getNameCn());
						newPc.setNameEn(pc.getNameEn());
						newPc.setParentId(pc.getId());
						newPc.setLevels((Integer)levelAndTurnnum[0]);
						newPc.setTurnnumber((Integer)levelAndTurnnum[1]);
						newPc.setPath((String)levelAndTurnnum[2] + "/" + pc.getId());
						newPc.setIsIndependent((Integer)pc.getIsIndependent());
						
						String hql = "FROM ProductCategory AS pc WHERE pc.levels = ? and pc.islast = ? ";
						Object[] param = { levelAndTurnnum[0],1 };
						List pcList = findSomeByHQL.findDataByHql(hql, param);
						if(null != pcList && !pcList.isEmpty()){
							ProductCategory pc = (ProductCategory) pcList.get(0);
							pc.setIslast(0);
							commonservice.updateDemo(pc);
						}
						newPc.setIslast(1);
						
						commonservice.saveDemo(newPc);
						
						this.sendMsgAjax("success", null);
					}
					
				}else{
					this.sendMsgAjax("parentId", null);
				}
				
			}
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 查询产品类目详情
	 * @return
	 */
	public String productCategoryDetail(){
		if(null != pcId){
			String hql = "FROM ProductCategory AS pc WHERE pc.parentId = ? ORDER BY pc.turnnumber";
			Object[] param = { "root" };
			listPc = findSomeByHQL.findDataByHql(hql, param);
			for (int i = 0; i <listPc.size(); i++) {
				ProductCategory pc = (ProductCategory)listPc.get(i);
				pcMap.put(pc.getId(), pc.getNameCn());
			}
			pc = commonservice.findById(pcId, new ProductCategory());
		}
		return SUCCESS;
	}
	
	/**
	 * 修改产品类目 
	 * @throws Exception
	 */
	public void updateProductCategory() throws Exception{
		try{
			String adminId = (String)ActionContext.getContext().getSession().get("adminId");
			if(null == adminId){
				this.sendMsgAjax("login", null);
			}else{
				ProductCategory category = commonservice.findById(pcId, new ProductCategory());
				//如果只是修改类目的名字  和 是否独立类目(那么他的其他信息不变)
				if(pc.getParentId().trim().equals(category.getParentId().trim())){
					category.setNameCn(pc.getNameCn());
					category.setIsIndependent((Integer)pc.getIsIndependent());
					commonservice.updateDemo(category);
					this.sendMsgAjax("success", null);
				}else{
					if(category.getLevels()==2 || category.getLevels()==1){//如果是二级或者是一级
						String hql = "FROM ProductCategory AS pc WHERE pc.parentId = ? ORDER BY pc.turnnumber";
						Object[] param = { pc.getParentId() };
						List list = findSomeByHQL.findDataByHql(hql, param);
						//判断将要移到的类目中是否有子类
						if(list.isEmpty()){
							this.operateForUpdate(pcId);
							category.setTurnnumber(1);
						}else{
							//将要移到的类目的操作
							ProductCategory pc = (ProductCategory)list.get(list.size()-1);
							pc.setIslast(0);
							commonservice.updateDemo(pc);
							//本来类目的操作
							this.operateForUpdate(pcId);
							category.setTurnnumber(pc.getTurnnumber()+1);
						}
						
					}
					if("root".equals(pc.getParentId())){
						category.setLevels(1);
					}else{
						category.setLevels(2);
					}
					category.setNameCn(pc.getNameCn());
					category.setIsIndependent((Integer)pc.getIsIndependent());
					category.setParentId(pc.getParentId());
					category.setIslast(1);
					commonservice.updateDemo(category);
					this.sendMsgAjax("success", null);
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 修改产品时调用的方法(主要来处理将要移动的类目的操作)
	 * @throws Exception
	 */
	public void operateForUpdate(String pcId) throws Exception{
		//本来类目的操作
		String hql1 = "FROM ProductCategory AS pc WHERE pc.id = ? ORDER BY pc.turnnumber";
		Object[] parem1 = { pcId };
		List list1 = findSomeByHQL.findDataByHql(hql1, parem1);
		ProductCategory pc1 = (ProductCategory)list1.get(0);//将要修改的类目
		String parenId = pc1.getParentId();
		
		String hql2 = "FROM ProductCategory AS pc WHERE pc.parentId = ? ORDER BY pc.turnnumber";
		Object[] parem2 = { parenId };
		List list2 = findSomeByHQL.findDataByHql(hql2, parem2);//跟修改的类目同一个父类的类目集合
		int listSize = list2.size();
		ProductCategory pc3 = (ProductCategory)list2.get(listSize-1);//拿到本类的最后一个类目
		//判断要移动的类目是不是本类目的最后一位(如果不是的话就要对他后面的类目重新排序)
		if(pc3.getId()==pcId){
			if(listSize>=2){
				ProductCategory pc4 = (ProductCategory)list2.get(listSize-2);
				pc4.setIslast(1);
				commonservice.updateDemo(pc4);
			}
		}else{
			for (int j = 1; j <= listSize-pc1.getTurnnumber(); j++) {
				ProductCategory pc5 = (ProductCategory) list2.get(pc1.getTurnnumber()-1+j);
				pc5.setTurnnumber(pc1.getTurnnumber()-1+j);
				commonservice.updateDemo(pc5);
				if(j==listSize-pc1.getTurnnumber()){
					pc5.setIslast(1);
					commonservice.updateDemo(pc5);
				}
			}
		}
	}
	/**
	 * 删除产品类目
	 * @throws Exception
	 */
	public void deleteProductCategory() throws Exception{
		try{
			String adminId = (String)ActionContext.getContext().getSession().get("adminId");
			if(null == adminId){
				this.sendMsgAjax("login", null);
			}else{
				
				String[] ids = pcId.split(",");
				int length = ids.length;
				for(int i=0;i<length;i++){
					ProductCategory category = commonservice.findById(ids[i], new ProductCategory());
					if(null != category){
						List list = this.getCategoryList(category.getId(), null);
						if(null != list)
							commonservice.deleteAll(list);
						String hql = "FROM Product p WHERE p.category.id = ? OR p.category.path like '%" + category.getId() + "%'";
						Object[] param = { category.getId() };
						List listProduct = findSomeByHQL.findDataByHql(hql, param);
						if(null != listProduct)
							commonservice.deleteAll(listProduct);
						commonservice.deleteDemo(category, null);
					}
				}
				
				this.sendMsgAjax("success", null);
			}
			
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 查询类目列表
	 * @return
	 */
	public String listCategory(){
		listPc = this.getCategoryList("root", null);
		return SUCCESS;
	}
	
	/**
	 * AJAX查询类目列表
	 * @return
	 */
	public void loadProductCategory() throws Exception{
		listPc = this.getCategoryList("root", null);
		if(null != listPc){
			List list = new ArrayList();
			int size = listPc.size();
			for(int i=0;i<size;i++){
				ProductCategory psc = (ProductCategory)listPc.get(i);
				ProductCategoryBean pcb = new ProductCategoryBean();
				pcb.setId(psc.getId());
				pcb.setNameCn(psc.getNameCn());
				pcb.setNameEn(psc.getNameEn());
				pcb.setLevels(psc.getLevels());
				pcb.setTurnnumber(psc.getTurnnumber());
				list.add(pcb);
			}
			String jsonResult = this.changeListToStr(list);
			this.sendMsgAjax(jsonResult, null);
		}
		
	}
	
	/**
	 * 调整类目顺序,选中的类目向上移动一位
	 * @throws Exception
	 */
	public void productCategoryUp() throws Exception{
		try{
			
			ProductCategory category = commonservice.findById(pcId, new ProductCategory());
			this.changePosition(category.getParentId(), category.getTurnnumber(), "up");
			
			this.sendMsgAjax("success", null);
			
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 调整类目顺序,选中的类目向下移动一位
	 * @throws Exception
	 */
	public void productCategoryDown() throws Exception{
		try{
			
			ProductCategory category = commonservice.findById(pcId, new ProductCategory());
			this.changePosition(category.getParentId(), category.getTurnnumber(), "down");
			
			this.sendMsgAjax("success", null);
			
		}catch (Exception e) {
			e.printStackTrace();
			this.sendMsgAjax("error", null);
		}
	}
	
	/**
	 * 首页的类目列表
	 * @return
	 */
	public String indexCategory(){
		if(null == pcId || "".equals(pcId.trim())){
			pcId = "root";
		}
		
		String hql = "FROM ProductCategory pc WHERE pc.parentId = ? ORDER BY pc.turnnumber";
		Object[] param = { pcId };
		List list = findSomeByHQL.findDataByHql(hql, param);
		if(null != list && list.size() > 0){
			int size = list.size();
			listPc = new ArrayList();
			String hqlChildren = "FROM ProductCategory pc WHERE pc.parentId = ? ORDER BY pc.turnnumber";
			for(int i=0;i<size;i++){
				ProductCategory pcIndex = (ProductCategory)list.get(i);
				List listChildren = findSomeByHQL.findDataByHql(hqlChildren, new Object[]{ pcIndex.getId() });
				Object[] obj = new Object[]{ pcIndex, listChildren };
				listPc.add(obj);
			}
		}
		return SUCCESS;
	}

	
	/**
	 * 获取新孩子的等级与排序号
	 * @param parentPcId
	 * @return
	 */
	private Object[] getLevelAndTurnnum(String parentPcId){
		
		ProductCategory pc = commonservice.findById(parentPcId, new ProductCategory());
		
		if(null != pc){
			int newLevels = pc.getLevels() + 1;
			
			String hql = "SELECT MAX(pc.turnnumber) FROM ProductCategory AS pc WHERE pc.parentId = ?";
			Object[] param = { parentPcId };
			List list = findSomeByHQL.findDataByHql(hql, param);
			int turnnum = 0;
			if(null != list && list.size() != 0){
				if(null != list.get(0))
					turnnum = (Integer)list.get(0);
			}
			turnnum = turnnum + 1;
			Object[] result = { newLevels, turnnum, pc.getPath() };
			
			return result;
		}else if("root".equals(parentPcId)){
			int newLevels = 1;
			
			String hql = "SELECT MAX(pc.turnnumber) FROM ProductCategory AS pc WHERE pc.parentId = ?";
			Object[] param = { parentPcId };
			List list = findSomeByHQL.findDataByHql(hql, param);
			int turnnum = 0;
			if(null != list && list.size() != 0){
				if(null != list.get(0))
					turnnum = (Integer)list.get(0);
			}
			turnnum = turnnum + 1;
			Object[] result = { newLevels, turnnum, "/root" };
			
			return result;
		}else{
			Object[] result = { 0, 0, null };
			
			return result;
		}
		
	}
	
	/**
	 * 通过递归获取类目列表
	 * @param parentId 父类目的ID
	 * @param resultList 保存结果的List
	 * @return 
	 */
	private List getCategoryList(String parentId, List resultList){
		if(null == parentId){
			parentId = "root";
		}
		if(null == resultList){
			resultList = new ArrayList();
		}
		
		String hql = "FROM ProductCategory AS pc WHERE pc.parentId = ? ORDER BY pc.turnnumber";
		Object[] param = { parentId };
		List list = findSomeByHQL.findDataByHql(hql, param);
		if(null != list && 0 != list.size()){
			int size = list.size();
			for(int i=0; i<size; i++){
				ProductCategory category = (ProductCategory)list.get(i);
				resultList.add(category);
				resultList = getCategoryList(category.getId(), resultList);
			}
		}
		
		return resultList;
		
	}
	
	/**
	 * 类目顺序升降
	 * @param parentId 当前类目的父类目ID
	 * @param turnnumber 当前类目的排序号
	 * @param type 升降类型(up 或 down)
	 */
	private void changePosition(String parentId, Integer turnnumber, String type){
		try{
			String hql = "FROM ProductCategory AS pc WHERE pc.parentId = ?";
			Object[] param = { parentId };
			List list = findSomeByHQL.findDataByHql(hql, param);
			int size = list.size();
			type = type.toLowerCase();
			if("up".equals(type)){
				if(turnnumber > 1){
					int num = 0;
					if(size >= 2){
						for(int i=0; i<size; i++){
							ProductCategory category = (ProductCategory)list.get(i);
							if(turnnumber == category.getTurnnumber()){
								
								if(islast != null && "1".equals(islast)){
									category.setIslast(0);
								}
								
								category.setTurnnumber(turnnumber - 1);
								num ++;
							}else if(turnnumber - 1 == category.getTurnnumber()){
								
								if(islast != null && "1".equals(islast)){
									category.setIslast(1);
								}
								
								category.setTurnnumber(turnnumber);
								num ++;
							}
							commonservice.updateDemo(category);
							if(2 == num){
								break;
							}
						}
					}
				}
			}else if("down".equals(type)){
				if(turnnumber < size){
					int num = 0;
					if(size >= 2){
						for(int i=0; i<size; i++){
							ProductCategory category = (ProductCategory)list.get(i);
							if(turnnumber == category.getTurnnumber()){
								
								if(size-category.getTurnnumber()==1){
										category.setIslast(1);
								}
								
								category.setTurnnumber(turnnumber + 1);
								num ++;
							}else if(turnnumber + 1 == category.getTurnnumber()){
								if(size-category.getTurnnumber()==0){
									category.setIslast(0);
								}
								category.setTurnnumber(turnnumber);
								num ++;
							}
							commonservice.updateDemo(category);
							if(2 == num){
								break;
							}
						}
					}
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取所有产品类型 
	 */
	public String categoryid(String pcId,int num)throws Exception{
		
	//	String str="<option value=\"\">选择产品类型</option>";
		
		String str = "";
		
		if(pcId == null || "null".equals(pcId) || pcId.isEmpty()){
			pcId = "root";
		}
		String hql = "FROM ProductCategory AS pc WHERE pc.parentId = ? ORDER BY pc.turnnumber";
		Object[] param = { pcId };
		List list = findSomeByHQL.findDataByHql(hql, param);
		
		if(null != list && !list.isEmpty()){
			String strA = "";
			
			if(num != 0){
				strA += "&nbsp;|-";
			}
			
			for(int i = 0;i<list.size();i++)
			{
				str += "<option value=\""+((ProductCategory)list.get(i)).getId()+"\">"+strA+((ProductCategory)list.get(i)).getNameCn()+"</option>";
				str += this.categoryid(((ProductCategory)list.get(i)).getId(),1);
			}
		}
		
		return str;
	}
	
	
	/**
	 *前台动态读取左侧类目
	 * @return
	 */
	public String category(){
		
		String hql = "FROM ProductCategory o  ORDER BY o.isIndependent asc,o.turnnumber asc ";
		
		List<ProductCategory> listTemp=findSomeByHQL.findDataByHql(hql);
		List<ProductCategory> temp=null;
		for(ProductCategory obj:listTemp){
			if(1==obj.getLevels()){
				listParent.add(obj);
			}else{
				temp=subMap.get(obj.getParentId());
				if(null==temp||temp.isEmpty()){
					temp=new ArrayList<ProductCategory>();
				}
				temp.add(obj);
			    subMap.put(obj.getParentId(), temp);
			}
		}
		
		return SUCCESS;
	}
	
	public void getcategoryid()throws Exception
	{
		String str = this.categoryid("root", 0);
		
		if(!str.isEmpty() && str != null){
			this.sendMsgAjax(str, null);
		}
	}
	
	
	
	public List<ProductCategory> getListParent() {
		return listParent;
	}
	public void setListParent(List<ProductCategory> listParent) {
		this.listParent = listParent;
	}
	public Map<String, List<ProductCategory>> getSubMap() {
		return subMap;
	}
	public void setSubMap(Map<String, List<ProductCategory>> subMap) {
		this.subMap = subMap;
	}
	public ProductCategory getPc() {
		return pc;
	}

	public void setPc(ProductCategory pc) {
		this.pc = pc;
	}

	public List getListPc() {
		return listPc;
	}

	public void setListPc(List listPc) {
		this.listPc = listPc;
	}

	public String getPcId() {
		return pcId;
	}

	public void setPcId(String pcId) {
		this.pcId = pcId;
	}

	public String getParentPcId() {
		return parentPcId;
	}

	public void setParentPcId(String parentPcId) {
		this.parentPcId = parentPcId;
	}

	public String getErrorinfo() {
		return errorinfo;
	}

	public void setErrorinfo(String errorinfo) {
		this.errorinfo = errorinfo;
	}
	
	public Map getPcMap() {
		return pcMap;
	}
	public void setPcMap(Map pcMap) {
		this.pcMap = pcMap;
	}
	
	public String getIslast() {
		return islast;
	}
	public void setIslast(String islast) {
		this.islast = islast;
	}
}
